<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

<title>Read Write Files in Ruby</title>

<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="Read Write Files in Ruby" />
<meta name="keywords" content="ruby file,ruby read file,ruby write file" />
<meta name="Distribution" content="Global" />
<meta name="author" content="Satish Talim / Original design: Erwin Aligam - ealigam@gmail.com" />
<meta name="copyright" content="Satish Talim 2007 and beyond..." />
<meta name="verify-v1" content="rFu86se+IkbtF+bH8mgJBKwU5HnKaSd8Ghw9umXQOkM=" />
<meta name="robots" content="index,follow" />
<meta http-equiv="Expires" content="0" />
<meta name="revisit-after" content="1 days" />

<link rel="stylesheet" href="/images/NewOrange.css" type="text/css" />
<link rel="stylesheet" href="/images/syntaxhighlighter.css" type="text/css" />
<link rel="icon" type="image/ico" href="/images/favicon.ico" />
<link href="https://plus.google.com/104011292189143717925/" rel="publisher" />
<!-- Google +1 button code -->
<link rel="canonical" href="/satishtalim/read_write_files.html" />
<script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script>
<!-- Google Analytics code -->
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-59044-10']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<!-- Google Analytics code ends -->
</head>

<body>
<!-- wrap starts here -->
<div id="wrap">

    <div id="header">

        <h1 id="logo">Ruby<span class="orange">Learning.github.io</span></h1>
        <h2 id="slogan">Helping Ruby Programmers become Awesome!</h2>

    </div>

    <div id="menu">
        <ul>
            <li><a href="/" title="Home page for rubylearning.github.io">Home</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Get started Learning Ruby here...">Tutorial</a></li>
            <li><a href="/download/downloads.html" title="Download this tutorial as an eBook">Downloads</a></li>
            <li><a href="/other/testimonials.html" title="People around the world who benefited from this site">Testimonials</a></li>
            <li><a href="/other/certification.html" title="Get certified in Ruby">Certification</a></li>
            <li><a href="/satishtalim/ruby_guide.html" title="Ruby Guide, Mentor">Mentor</a></li>
            <li><a href="https://blog.rubylearning.github.io/" title="Ruby blog of Ruby Learning site">Blog</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Online Ruby Course">Online Course</a></li>
            <li><a href="http://ruby-challenge.rubylearning.github.io/" title="Ruby Programming Challenge for Newbies">Challenge</a></li>
            <li><a href="/satishtalim/about.html" title="Information about Satish Talim">About</a></li>
        </ul>
    </div>

    <!-- content-wrap starts here -->
    <div id="content-wrap">

            <div id="main">

                <div id="main-inner"><a name="TemplateInfo"></a>
                <h1>Read/Write Text Files</h1>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/ruby_random_numbers.html">&lt;Random Numbers | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/ruby_regular_expressions.html">Regular Expressions&gt;</a>
                  </strong>
                </p>

                <p>Let's look at how we can read / write to a text file with the help of a simple program <strong>p027readwrite.rb</strong></p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p027readwrite.rb
                # Open and read from a text file
                # Note that since a block is given, file will
                # automatically be closed when the block terminates
                File.open('p014constructs.rb', 'r') do |f1|
                  while line = f1.gets
                    puts line
                  end
                end

                # Create a new file and write to it
                File.open('test.rb', 'w') do |f2|
                  # use "\n" for two lines of text
                  f2.puts "Created by Satish\nThank God!"
                end
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The <strong>File.open</strong> method can open the file in different modes like 'r' Read-only, starts at beginning of file (default); 'r+' Read/Write, starts at beginning of file; 'w' Write-only, truncates existing file to zero length or creates a new file for writing. File modes can work like:</p>
                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                &lt;file mode&gt;&lt;:external encoding&gt;&lt;:internal&gt;
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Let us say you know that the external encoding is in UTF-16LE and you want the internal in UTF-8, then you can write:</p>
                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                File.open('p014constructs.rb', 'r:UTF-16LE:UTF-8') do |f1|
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Please check the <a href="http://ruby-doc.org/core-2.3.0/File.html">online documentation</a> for a full list of modes available. <strong>File.open</strong> opens a new File if there is no associated block. If the optional block is given, it will be passed file as an argument, and the file will automatically be closed when the block terminates. <em>Always close a file that you open. In the case of a file open for writing, this is very important and can actually prevent lost data</em>.
                </p>

                <p><strong>File</strong> implements a <strong>readlines</strong> method that reads an entire file into an array, line by line.</p>

                <p class="post-note">Both class methods <strong>open</strong> and <strong>readlines</strong> belong to the <strong>IO</strong> class, whose sub-class is <strong>File</strong>. We have not done classes, objects, inheritance yet but for the record these two methods are inherited by the sub-class <strong>File</strong> from the class <strong>IO</strong>.</p>

                <h3>Traversing Directory Trees</h3>

                <p>The <strong>Find</strong> module supports top-down traversal of a set of file paths, given as arguments to the <strong>find</strong> method. If an argument is a directory, then its name and name of all its files and sub-directories will be passed in (in the example below, this would be from where you run this program).</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                require 'find'
                Find.find('./') do |f|
                  type = case
                         when File.file?(f) then "F"
                         when File.directory?(f) then "D"
                         else "?"
                         end
                  puts "#{type}: #{f}"
                end
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>We shall talk about <strong>require</strong> soon <a href="/satishtalim/including_other_files_in_ruby.html">here</a>.</p>

                <h3>Random Access</h3>

                <p>It's quite easy to access a file randomly. Let's say we have a text file (named <strong>hellousa.rb</strong>), the contents of which is shown below:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                puts 'Hello USA'
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>We now need to display the contents of the file from the word USA. Here's how - program <strong>p028xrandom.rb</strong>:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                # p028xrandom.rb
                # We now need to display the contents of the file from the word USA
                f = File.new("hellousa.rb")

                # SEEK_CUR - Seeks to first integer number parameter plus current position
                # SEEK_END - Seeks to first integer number parameter plus end of stream
                #   (you probably want a negative value for first integer number parameter)
                # SEEK_SET - Seeks to the absolute location given by first integer number parameter
                # :: is the scope operator - more on this later
                f.seek(12, IO::SEEK_SET)
                print f.readline
                f.close
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The output is:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                >ruby p028xrandom.rb
                USA'
                >Exit code: 0
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Ruby supports the notion of a file pointer. The file pointer indicates the current location in the file. The <strong>File.new</strong> method opens the file 'hellousa.rb' in <em>read-only mode</em> (default mode), returns a new <strong>File</strong> object and the file pointer is positioned at the beginning of the file. In the above program, the next statement is <strong>f.seek(12, IO::SEEK_SET)</strong>. The <strong>seek</strong> method of class <a href="http://www.ruby-doc.org/core-1.9.3/IO.html">IO</a>, moves the file pointer to a given integer distance (first parameter of <strong>seek</strong> method) in the stream according to the value of the second parameter in the <strong>seek</strong> method.</p>

                <ul>
                  <li><strong>IO::SEEK_CUR</strong> - Seeks to first integer number parameter plus current position</li>
                  <li><strong>IO::SEEK_END</strong> - Seeks to first integer number parameter plus end of stream (you probably want a negative value for first integer number parameter)</li>
                  <li><strong>IO::SEEK_SET</strong> - Seeks to the absolute location given by first integer number parameter</li>
                </ul>

                <p>More on the scope operator <strong>::</strong> <a href="/satishtalim/ruby_constants.html">here</a>.</p>

                <h3>Does Ruby allow Object Serialization?</h3>

                <p>Java features the ability to serialize objects, letting you store them somewhere and reconstitute them when needed. Ruby calls this kind of serialization marshaling. Saving an object and some or all of its components is done using the method <strong>Marshal.dump</strong>. Later on you can reconstitute the object using <strong>Marshal.load</strong>. Ruby uses marshaling to store session data. Refer topic <a href="/satishtalim/object_serialization.html">Object Serialization</a> later on.</p>
<!--
                <p>Get the best out of your mouse by using it on an <em><a href="http://www.myshopping.com.au/PT--288_Computer_Accessories_Corsair_Memory_Mouse_Mats__fs_868_49874_e__">optimized Corsair mouse mat</a>.</em></p>
-->
                <h3>Summary</h3>

                <p>I have listed down all the <strong><a href="/satishtalim/ruby_summary4.html">important points</a></strong> you need to remember after you have completed the following topics: <a href="/satishtalim/ruby_arrays.html">Arrays</a>, <a href="/satishtalim/ruby_ranges.html">Ranges</a>, <a href="/satishtalim/ruby_symbols.html">Symbols</a>, <a href="/satishtalim/ruby_hashes.html">Hashes</a>, <a href="/satishtalim/ruby_random_numbers.html">Random Numbers</a>, <a href="/satishtalim/read_write_files.html">Read/Write Text Files</a>.</p>

                <p style="background-color: #FAFAFA; padding: 5px; margin-top: 20px; font-size: 65%;"><strong>Note</strong>: The Ruby Logo is Copyright (c) 2006, Yukihiro Matsumoto. I have made extensive references to information, related to Ruby, available in the public domain (wikis and the blogs, articles of various <span style="font-weight: bold;" title="Click Gurus on the menu above">Ruby Gurus</span>), my acknowledgment and thanks to all of them. Much of the material on <a href="/">rubylearning.github.io</a> and in the course at <a href="http://rubylearning.org/">rubylearning.org</a> is drawn <strong>primarily</strong> from the <strong>Programming Ruby book</strong>, available from <a href="http://pragprog.com/book/ruby3/programming-ruby-1-9-2-0">The Pragmatic Bookshelf</a>.</p>

                <p class="post-footer align-right">
                  <strong>
                    <a href="/satishtalim/ruby_random_numbers.html">&lt;Random Numbers | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/ruby_regular_expressions.html">Regular Expressions&gt;</a>
                  </strong>
                </p>

            </div>
            <!-- main inner ends here -->
        </div>

            <div id="rightbar">
            </div>

    <!-- content-wrap ends here -->
    </div>

<!-- wrap ends here -->
</div>

<!-- footer starts here -->
<div id="footer">
    <!-- CHANGE THE FOOTER -->
    <p>&copy; 2006-2021 <strong>rubylearning.github.io - A Ruby Tutorial</strong>&nbsp;&nbsp;Page Updated: 5th Jan. 2021 | Design: <a href="mailto:ealigam@gmail.com">Erwin Aligam</a> | Valid: <a href="http://validator.w3.org/check/referer">XHTML</a> | <a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/">Home</a> | <a href="/privacy.html">Privacy</a> | <a href="/sitemap.html">Sitemap</a></p>
</div>
<!-- footer ends here -->

<!-- SyntaxHighlighter code -->
<script src="/js/shCore.js" type="text/javascript"></script>
<script src="/js/shBrushRuby.js" type="text/javascript"></script>
<script type="text/javascript">
dp.SyntaxHighlighter.HighlightAll('code');
</script>
<!-- SyntaxHighlighter code -->
</body>
</html>
